package com.mobilepoc.jersey.location;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.mobilepoc.jersey.model.Coordinates;
import com.mobilepoc.jersey.model.Location;

@Path("/location")
public class LocationRetrieverImpl implements LocationRetriever {

	/**
	 * {@inheritDoc}
	 */
	@GET
	@Path("/{latitude}/{longitude}")
    @Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Override
	public Location getClosestLocationByGivenCoordinates(@PathParam("latitude") double latitude, @PathParam("longitude") double longitude) {
		Coordinates coordinatesOfUser=new Coordinates(latitude, longitude);
		Coordinates coordinatesOfBankLocation=null;
		double closestsDistance=10000.0; //Anything longer than the equator should do fine.
		AvailableLocation closest = null;
		
		for (AvailableLocation location : AvailableLocation.values()) {
			coordinatesOfBankLocation=new Coordinates(location.getLatitude(), location.getLongitude());
			double distanceCandidate=DistanceCalculator.calculateDistance(coordinatesOfUser, coordinatesOfBankLocation);
			if(distanceCandidate<closestsDistance){
			    closest=location;
			    closestsDistance=distanceCandidate;
			}
		}
		
		Location location = new Location(new Coordinates(closest.getLatitude(), closest.getLongitude()));
		location.setName(closest.getName());
		return location;
	}


}
